/*
 * Copyright (C) 2010 Yigal Duppen
 *
 * This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package nl.scalasim
package testsupport

trait FixtureRuleSet extends RuleSet {
  self: Controller =>

  private var idleHarvesters = List[Harvester]()  // harvesters w/o producer
  private var idleCitizens = List[Citizen]()  // citizens w/o harvester

  private var unusedProducers = List[Producer]()  // producers w/o harvester
  private var unusedHarvesters = List[Harvester]() // harvesters w/o citizen


  def actorAdded(a: ScalasimActor) {
    a match {
      case c: Citizen => {
        idleCitizens :+= c
      }
      case h: Harvester => {
        idleHarvesters :+= h
        unusedHarvesters :+= h
      }
      case p: Producer => {
        unusedProducers :+= p
      }
    }

    // for each idle citizen: remove a matching harvester from the
    // unusedHarvester and connect it to the citizen; remove the citizen
    // from the idle citizens list
    idleCitizens foreach { c =>
      unusedHarvesters.headOption match {
        case None => ()
        case Some(h) => {
          c.workAt(h)
          unusedHarvesters = unusedHarvesters - h
          idleCitizens = idleCitizens - c
        }
      }
    }

    // for each idle harvester: remove a matching producer from the
    // unusedProducers and connect it to the harvester; remove the
    // harvester from the idle harvesters list
    idleHarvesters foreach { h =>
      (unusedProducers filter { p => p.goods == h.goods}).headOption match {
        case None => ()
        case Some(p) => {
          h.connectTo(p)
          unusedProducers = unusedProducers - p
          idleHarvesters = idleHarvesters - h
        }
      }
    }
  }


  override def beforeTick() = {
    self.addActor(self.setting.newCitizen())
  }
}